from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import Permission

class Role(models.Model):
    """
    Role table
    Used to define roles within the system
    """
    role_id = models.AutoField(primary_key=True)
    role_name = models.CharField(max_length=50, unique=True, null=False, verbose_name="Role Name")
    description = models.TextField(blank=True, null=True, verbose_name="Description")
    created_at = models.DateTimeField(default=now, verbose_name="Created At")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated At")

    class Meta:
        verbose_name = "Role"
        verbose_name_plural = "Roles"
        ordering = ['-created_at']

    def __str__(self):
        return self.role_name


class RolePermission(models.Model):
    """
    Role Permission Mapping table
    Used to define many-to-many relationship between roles and permissions
    """
    id = models.AutoField(primary_key=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name="permissions", verbose_name="Role")
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, related_name="roles", verbose_name="Permission")
    created_at = models.DateTimeField(default=now, verbose_name="Created At")

    class Meta:
        verbose_name = "Role Permission Mapping"
        verbose_name_plural = "Role Permission Mappings"
        unique_together = ('role', 'permission')  # Prevent duplicate assignment of the same permission to the same role

    def __str__(self):
        return f"{self.role.role_name} -> {self.permission.codename}"